package cn.com.xy.sms.sdk.db.entity;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.queue.util.ResourseUtil;
import cn.com.xy.sms.sdk.util.JsonUtil;
import cn.com.xy.sms.sdk.util.StringUtils;

public class ResourseManager {

    public static final String TABLE_NAME = "tb_resourse_queue";
    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;

    public static String getCreateTableSql() {
        return " create table  if not exists " + TABLE_NAME + " (" + " id INTEGER PRIMARY KEY," + " res_type INTEGER,"
                + " res_version INTEGER," + " res_url TEXT," + " down_statu INTEGER DEFAULT '0',"
                + " temp_filename TEXT," + " down_failed_time LONG DEFAULT '0')";
    }

    /**
     * 必须要把所有未下载的记录按顺序查询出来，再在去判断时间是不是超过了一个小时
     * 否则，假如把时间写到了sql的条件里。查出来的数据，可能就会不按res_version的顺序了。
     * 
     * @param res_type
     * @return
     */
    public static JSONArray queryNeedDownResourse(int res_type) {
        XyCursor cursor = null;
        JSONArray jsonArr = null;
        String where = "res_type = ? and down_statu = ? ";
        try {
            String[] columns = new String[] { "id", "res_type", "res_version", "res_url", "down_statu",
                    "temp_filename", "down_failed_time" };
            cursor = DBManager.query(TABLE_NAME, columns, where, new String[] { res_type + "", 0 + "" }, null, null,
                    "res_version asc", null);


            if (cursor != null && cursor.getCount() > 0) {
                int idIndex = cursor.getColumnIndex("id");
                int res_typeIndex = cursor.getColumnIndex("res_type");
                int res_versionIndex = cursor.getColumnIndex("res_version");
                int res_urlIndex = cursor.getColumnIndex("res_url");
                int down_statuIndex = cursor.getColumnIndex("down_statu");
                int temp_filenameIndex = cursor.getColumnIndex("temp_filename");
                int down_failed_timeIndex = cursor.getColumnIndex("down_failed_time");

                JSONObject tempObj = null;
                jsonArr = new JSONArray();
                while (cursor.moveToNext()) {
                    tempObj = new JSONObject();
                    tempObj.put("id", cursor.getInt(idIndex));
                    tempObj.put("res_type", cursor.getInt(res_typeIndex));
                    tempObj.put("res_version", cursor.getInt(res_versionIndex));
                    tempObj.put("res_url", cursor.getString(res_urlIndex));
                    tempObj.put("down_statu", cursor.getInt(down_statuIndex));
                    tempObj.put("temp_filename", cursor.getString(temp_filenameIndex));
                    tempObj.put("down_failed_time", cursor.getLong(down_failed_timeIndex));

                    jsonArr.put(tempObj);
                }

            }

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "queryNeedDownResourse: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
        return jsonArr;
    }

    public static String queryNeedCheckResourse(int res_type) {
        XyCursor cursor = null;
        String res_version = "";
        try {

            String where = "res_type = " + res_type + " ORDER BY res_version desc LIMIT 1 ";
            cursor = DBManager.query(TABLE_NAME, new String[] { "res_version" }, where, null);
            if (cursor != null && cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    res_version = cursor.getString(0);
                }
            }

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.e(Constant.TAG, "queryNeedCheckResourse: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
        return res_version;
    }

    /**
     * 处理返回的JSONArray
     * 
     * @param JSONArray
     */
    public static void handleJSONArray(JSONArray JSONArray) {
        try {
            if (JSONArray != null && JSONArray.length() > 0) {
                int size = JSONArray.length();
                for (int i = 0; i < size; i++) {
                    JSONObject json = JSONArray.getJSONObject(i);
                    String del_history = (String) JsonUtil.getValueFromJsonObject(json, "del_history");
                    // 假如需要删除之前版本的，删除之前版本
                    if (!StringUtils.isNull(del_history) && del_history.equals("1")) {
                        deleteResourse(json);
                    }
                    insertOrUpdateResourse(json);

                }
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "handleJSONArray: ", e);
            /* SDK-550 hewengao 20160719 end */
        }
    }

    /**
     * 删除数据库里，这个版本之前的所有记录
     * 
     * @param jsonObject
     */
    public static void deleteResourse(JSONObject jsonObject) {
        try {
            if (jsonObject != null) {
                String res_type = (String) JsonUtil.getValueFromJsonObject(jsonObject, "res_type");
                String res_version = (String) JsonUtil.getValueFromJsonObject(jsonObject, "res_version");

                DBManager.delete(TABLE_NAME, "res_type = ? and res_version < ?", new String[] { res_type + "",
                        res_version + "" });
                // 删除临时文件
                ResourseUtil.deleteTempZip(res_type, res_version);

            }

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "deleteResourse: ", e);
            /* SDK-550 hewengao 20160719 end */
        }
    }

    public static void insertOrUpdateResourse(JSONObject jsonObject) {
        XyCursor xyCursor = null;
        try {
            String res_type = (String) JsonUtil.getValueFromJsonObject(jsonObject, "res_type");
            String res_version = (String) JsonUtil.getValueFromJsonObject(jsonObject, "res_version");

            if (jsonObject != null) {
                xyCursor = DBManager.query(TABLE_NAME, new String[] { res_type + "", res_version + "" },
                        "res_type = ? and res_version = ? ", new String[] { res_type + "", res_version + "" });
                ContentValues values = new ContentValues();
                values.put("res_type", res_type);
                values.put("res_version", res_version);
                values.put("res_url", (String) JsonUtil.getValueFromJsonObject(jsonObject, "res_url"));
                if (xyCursor != null && xyCursor.getCount() > 0) {
                    DBManager.update(TABLE_NAME, values, "res_type = ? and res_version = ? ", new String[] {
                            res_type + "", res_version + "" });
                } else {
                    DBManager.insert(TABLE_NAME, values);
                }
            }

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "insertOrUpdateResourse: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }
    }

    /**
     * 0:待下载 1:已下载（下载后将同时将res_url置空） 2:已入库或已解压
     * 
     * @param unzipSuess
     * @param fileName
     */
    public static void UpdateResourse(boolean unzipSuess, String fileName) {
        try {
            ContentValues values = new ContentValues();
            int down_statu = 0;
            if (unzipSuess) {
                down_statu = 2;
            }
            values.put("down_statu", down_statu);
            DBManager.update(TABLE_NAME, values, "temp_filename = ?", new String[] { fileName });

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "UpdateResourse: ", e);
            /* SDK-550 hewengao 20160719 end */
		}
	}
	/**
	 * 
	 * @param id
	 * @param isSucess
	 * @param fileName
	 */
	public static void UpdateResourse(Integer id,boolean isSucess,String fileName){
		try {
			  ContentValues values = new ContentValues();    
			 if(isSucess)
			 {
				 values.put("res_url", "");
				 values.put("down_failed_time", "0");
				 values.put("down_statu", "1");
				 values.put("temp_filename", fileName);
			 }
			 else
			 {
				 values.put("down_failed_time", System.currentTimeMillis());
				 values.put("down_statu", "0");
				 values.put("temp_filename", fileName);
			 }
			 DBManager.update(TABLE_NAME, values, "id = ? ",
					 new String[] {id+""});
		} catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "UpdateResourse: ", e);
            /* SDK-550 hewengao 20160719 end */
        }
		
	}
}
